<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta property="og:type" content="website">
<meta property="og:title" content="汇话板">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/page/5/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="William Leung">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/page/5/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner index posts-expand">
      

      
    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E03/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E03/" class="post-title-link" itemprop="url">《你不知道的JavaScript(上)》S01E03</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-11-29 22:14:17" itemprop="dateCreated datePublished" datetime="2020-11-29T22:14:17+08:00">2020-11-29</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2020-12-01 23:07:28" itemprop="dateModified" datetime="2020-12-01T23:07:28+08:00">2020-12-01</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E4%B8%80%E5%91%A8%E4%B8%80%E7%AB%A0%E5%89%8D%E7%AB%AF%E4%B9%A6/" itemprop="url" rel="index"><span itemprop="name">一周一章前端书</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>3.4k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>3 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="第3章：函数作用域和块级作用域"><a href="#第3章：函数作用域和块级作用域" class="headerlink" title="第3章：函数作用域和块级作用域"></a>第3章：函数作用域和块级作用域</h1><h2 id="3-1-函数中的作用域"><a href="#3-1-函数中的作用域" class="headerlink" title="3.1 函数中的作用域"></a>3.1 函数中的作用域</h2><ul>
<li> <strong>JavaScript变量的查找规则是由内到外的</strong> ，阅读如下代码：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> b = <span class="number">2</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="comment">//...</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> c = <span class="number">3</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">bar();  <span class="comment">//失败</span></span><br><span class="line"><span class="built_in">console</span>.log(a,b,c); <span class="comment">//失败</span></span><br></pre></td></tr></table></figure></li>
<li><code>foo()</code>函数作用域声明了变量<code>a</code>、<code>b</code>、<code>c</code>以及函数<code>bar</code>，如果在外部使用这些函数内的变量或函数都会失败。</li>
<li> <strong>函数作用域的含义就是说，函数内的变量只允许在函数范围内使用（也包括在内部嵌套函数）。</strong></li>
</ul>
<h2 id="3-2-隐藏内部实现"><a href="#3-2-隐藏内部实现" class="headerlink" title="3.2 隐藏内部实现"></a>3.2 隐藏内部实现</h2><ul>
<li>既然函数中变量的活动范围只限制在函数内，反过来其实也可以这么理解：</li>
<li>我们挑选一个代码片段，用函数作用域将其包装起来了，而 <strong>函数内的具体细节(变量)对外不可见，被“隐藏”起来了。</strong></li>
<li>这种做法就是 <strong>软件设计中的<code>最小授权</code>或<code>最小暴露原则</code></strong> 。</li>
<li>如果所有变量和函数都声明到全局作用域中，可能会发生无法预知的情况：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> b;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    b = a + doSomethingElse(a * <span class="number">2</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(b * <span class="number">3</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">doSomethingElse</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a - <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">doSomething(<span class="number">2</span>); <span class="comment">//15</span></span><br></pre></td></tr></table></figure>
通过函数作用域修改后，是不是更安心了：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">doSomething</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> b;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">doSomethingElse</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> a - <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    b = a + doSomethingElse(a * <span class="number">2</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(b * <span class="number">3</span>);</span><br><span class="line">&#125;</span><br><span class="line">doSomething(<span class="number">2</span>); <span class="comment">//15</span></span><br></pre></td></tr></table></figure></li>
<li>另外，<strong>通过作用域隐藏变量还有一个好处：可以避免因为同名造成的变量冲突。</strong><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">        i = <span class="number">3</span>;</span><br><span class="line">        <span class="built_in">console</span>.log(a + i);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;<span class="number">10</span>;i++)&#123;</span><br><span class="line">        bar(i * <span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">foo();  <span class="comment">//因为调用的i是通一个，造成无限循环</span></span><br></pre></td></tr></table></figure></li>
<li>针对同名变量冲突，大概有两种处理方式：<h4 id="1-全局命名空间"><a href="#1-全局命名空间" class="headerlink" title="(1) 全局命名空间"></a>(1) 全局命名空间</h4></li>
<li>将本来暴露在全局作用域的诸多变量，统一放到全局的某个对象中，这个对象看做一个命名空间。</li>
<li>jQuery采用的就是此类做法，将所有和jQuery关联的第三方插件，都放到jQuery对象下。</li>
</ul>
<h4 id="2-模块管理"><a href="#2-模块管理" class="headerlink" title="(2) 模块管理"></a>(2) 模块管理</h4><ul>
<li>如同<code>seaJS</code>、<code>requireJS</code>等现代化的模块机制一样</li>
<li>首先将JS第三方库统一注册到模块管理器中，当调用的方法需要某个库时，从模块管理器中将该库挑选出来，显式的注入到函数作用域里。</li>
<li>这样不仅避免了全局作用域的污染，更实现了按需加载。</li>
</ul>
<h2 id="3-3-函数作用域"><a href="#3-3-函数作用域" class="headerlink" title="3.3 函数作用域"></a>3.3 函数作用域</h2><ul>
<li>上文说到，通过函数作用域来隐藏变量能避免一系列的问题，但这并不是最理想的：<ul>
<li>为了隐藏几个变量，我还得声明一个具名函数，那这个函数本身，不也在污染全局作用域吗？</li>
<li>其次，声明了函数还得去调用才能运行起来。</li>
</ul>
</li>
<li>是否有可以 <strong>不用指定函数名，并且还能自动运行的函数</strong> 呢？答案是肯定的：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">(<span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">3</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(a); <span class="comment">//3</span></span><br><span class="line">&#125;)();</span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">//2 函数作用域对内部的a做了隐藏，不影响全局的作用域</span></span><br></pre></td></tr></table></figure></li>
<li><strong>当以<code>()</code>中括号包含函数时，则是函数表达式，而不是标准的函数声明。</strong></li>
<li>不要对函数表达式感到陌生，其实早在定时函数<code>setTimeout()</code>我们就有用到过：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;I waited 1 second!&#x27;</span>);</span><br><span class="line">&#125;,<span class="number">1000</span>);</span><br></pre></td></tr></table></figure></li>
<li>定时函数中用到的叫<code>匿名函数表达式</code>，因为没有指定函数名。</li>
<li>注意， <strong>函数表达式是可以匿名的，但函数声明则不允许匿名。</strong></li>
<li>使用函数表达式需要注意的几点：<ul>
<li>匿名函数不便于调试；</li>
<li>当函数需要引用自身的时候比较困难，只能引用已经过期的<code>arguments.callee</code>；</li>
<li>由于匿名函数缺乏函数名，代码的可读性较差；</li>
</ul>
</li>
<li>用<code>()</code>包含一个函数可以构造一个函数表达式，而 <strong>在末尾紧跟着一个<code>()</code>可以立即执行这个函数</strong> 。</li>
<li>JS社区将它命名为 __<code>IIFE(Immediately Invoked Function Expresion)</code>，代表立即执行的函数表达式__。</li>
<li>IIFE还有另外一种写法：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;test&#x27;</span>);</span><br><span class="line">&#125;())</span><br></pre></td></tr></table></figure></li>
<li><strong>IIFE可以传递参数</strong> ：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"><span class="built_in">global</span></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">3</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(a); <span class="comment">//3</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">global</span>.a);  <span class="comment">//2</span></span><br><span class="line">&#125;)(<span class="built_in">window</span>);</span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">//2</span></span><br></pre></td></tr></table></figure></li>
<li><strong>IIFE</strong> 还有一种 <strong>可以倒置代码的运行顺序</strong> 的玩法，这种模式在UMD（Universal Module Definition）项目中运用广泛：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">(<span class="function"><span class="keyword">function</span> <span class="title">iife</span>(<span class="params">def</span>)</span>&#123;</span><br><span class="line">    def(<span class="built_in">window</span>);</span><br><span class="line">&#125;)(<span class="function"><span class="keyword">function</span>(<span class="params"><span class="built_in">global</span></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">3</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(a); <span class="comment">//3</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">global</span>.a);  <span class="comment">//2</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="3-3-块作用域"><a href="#3-3-块作用域" class="headerlink" title="3.3 块作用域"></a>3.3 块作用域</h2><ul>
<li>虽然函数作用域是最常见的作用域，但JavaScript也有其他的作用域单元，甚至在很多场景下，甚至用这些非函数的作用域单元实现功能，代码会更简洁、更优雅。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//虽然i声明于for循环的花括号范围内</span></span><br><span class="line"><span class="comment">//但注意i是用var来声明的，实际上它是全局作用域下的变量</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;<span class="number">10</span>;i++)&#123;</span><br><span class="line">    consooe.log(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><code>for</code>循环中的<code>i</code>经常会由于忽略，会被绑定到全局作用域，而JavaScript的块级作用域就可以将变量限制在花括号的范围内。<h4 id="with"><a href="#with" class="headerlink" title="with"></a>with</h4></li>
<li>前文提到的<code>with</code>就可以构造块级作用域，但不提倡使用。<h4 id="try-catch"><a href="#try-catch" class="headerlink" title="try/catch"></a>try/catch</h4></li>
<li><code>catch</code>分句中，也会创建一个块级作用域。在其中声明的变量仅在<code>catch</code>内部有效。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>&#123;</span><br><span class="line">    makeError();</span><br><span class="line">&#125;<span class="keyword">catch</span>(err)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(err);</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(err);   <span class="comment">//ReferenceError: err not found</span></span><br></pre></td></tr></table></figure>
<h4 id="let"><a href="#let" class="headerlink" title="let"></a>let</h4></li>
<li>ES6引入了 <strong><code>let</code>关键字，可以将变量绑定到所在代码的作用域中</strong> （通常是花括号<code>&#123;&#125;</code>内）。换句话说，<code>let</code>为其声明的变量隐式的劫持了所在的块作用域。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = <span class="literal">true</span>;</span><br><span class="line"><span class="keyword">if</span>(foo)&#123;</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">let</span> bar = foo * <span class="number">2</span>;</span><br><span class="line">        bar = something(bar);</span><br><span class="line">        <span class="built_in">console</span>.log(bar);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(bar);   <span class="comment">//ReferenceError</span></span><br></pre></td></tr></table></figure></li>
<li>注意：但 <strong><code>let</code>关键字不会进行变量声明的提升</strong> ，请确保代码在运行时已进行声明。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(bar);   <span class="comment">//ReferenceError!</span></span><br><span class="line">    <span class="keyword">let</span> bar = <span class="number">2</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="const"><a href="#const" class="headerlink" title="const"></a>const</h4></li>
<li>ES6中的 __<code>const</code>同样也可以创建块级作用域变量，但变量值是固定的（常量）__。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = <span class="literal">true</span>;</span><br><span class="line"><span class="keyword">if</span>(foo)&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">const</span> b = <span class="number">3</span>;    <span class="comment">//在if块级作用域下的常量</span></span><br><span class="line">    </span><br><span class="line">    a = <span class="number">3</span>;  <span class="comment">//赋值正常</span></span><br><span class="line">    b = <span class="number">4</span>;  <span class="comment">//赋值失败！常量不能改变</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">//3</span></span><br><span class="line"><span class="built_in">console</span>.log(b); <span class="comment">//ReferenceError!</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="3-5-小结"><a href="#3-5-小结" class="headerlink" title="3.5 小结"></a>3.5 小结</h2><ul>
<li>函数是JavaScript中最常见的作用域单位，声明在函数内的变量会被函数作用域“隐藏”起来，这是软件设计的最小暴露原则。</li>
<li>函数不是唯一的作用域单位，块级作用域是指变量属于某个代码段（通常拥有花括号<code>&#123;&#125;</code>）下。</li>
<li><code>try/catch</code>的<code>catch</code>分句拥有块作用域。</li>
<li>ES6的<code>let</code>和<code>const</code>关键字能在任意代码段中创建块作用域变量。</li>
</ul>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E02/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E02/" class="post-title-link" itemprop="url">《你不知道的JavaScript(上)》S01E02</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-11-29 22:13:03" itemprop="dateCreated datePublished" datetime="2020-11-29T22:13:03+08:00">2020-11-29</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2020-12-01 23:07:29" itemprop="dateModified" datetime="2020-12-01T23:07:29+08:00">2020-12-01</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E4%B8%80%E5%91%A8%E4%B8%80%E7%AB%A0%E5%89%8D%E7%AB%AF%E4%B9%A6/" itemprop="url" rel="index"><span itemprop="name">一周一章前端书</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>2.4k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>2 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="第2章：词法作用域"><a href="#第2章：词法作用域" class="headerlink" title="第2章：词法作用域"></a>第2章：词法作用域</h1><ul>
<li>第一章提到，所谓作用域就是JavaScript变量的存取规则。</li>
<li>而众多编程语言的作用域规则中，一般有两套工作模式：<code>词法作用域</code>和<code>动态作用域</code>。</li>
<li><strong>JavaScript作用域采用的是<code>词法作用域</code></strong> ，以下主要讲解这种工作模式。</li>
</ul>
<h2 id="2-1-词法阶段"><a href="#2-1-词法阶段" class="headerlink" title="2.1 词法阶段"></a>2.1 词法阶段</h2><ul>
<li>本书第一章说，在编译时期会进行词法分析，即将文本内容分解成有意义的词法字符串。比如<code>var a = 2;</code>最终会分解成[<code>var</code>、<code>a</code>、<code>=</code>、<code>2</code>、<code>;</code>]</li>
<li>所谓 <strong><code>词法作用域</code>，就是在词法分析阶段就确定了变量处于哪个作用域，从而确定了变量可访问的范围。</strong><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> b = a * <span class="number">2</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">bar</span>(<span class="params">c</span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(a, b, c);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">foo(<span class="number">2</span>);  <span class="comment">//2, 4, 12</span></span><br></pre></td></tr></table></figure></li>
<li>分析如上代码：<ul>
<li>总共有3个作用域<ol>
<li><strong>全局作用域</strong> ，定义了<code>foo</code>函数；</li>
<li><strong><code>foo</code>函数作用域</strong> ，定义了形参<code>a</code>、函数<code>bar</code>和变量<code>b</code>；</li>
<li><strong><code>bar</code>函数作用域</strong> ，只定义了形参<code>c</code>；</li>
</ol>
</li>
<li>由此可见，<strong>变量的作用域，就相当于所在函数的花括号包含的范围（除了全局作用域），并且作用域之间是逐级嵌套的。</strong></li>
<li><strong>变量的查找是由内往外的。</strong> JS引擎执行代码<code>console.log(a, b, c)</code>;时：<ol>
<li>首先是从<code>bar</code>函数作用域中查找<code>a</code>，<code>b</code>，<code>c</code>三个变量，只找到变量<code>c</code>；</li>
<li>接着到上一级的<code>foo</code>函数作用域，查到了变量<code>a</code>和<code>b</code>；</li>
</ol>
</li>
<li><strong>在多个作用域层嵌套的情况下，当子级作用域包含有父级作用域同名的变量时，则忽略父级变量，直接使用子级的变量，这称为“<code>遮蔽效应</code>”。</strong></li>
</ul>
</li>
</ul>
<h2 id="2-2-欺骗词法"><a href="#2-2-欺骗词法" class="headerlink" title="2.2 欺骗词法"></a>2.2 欺骗词法</h2><ul>
<li>既然变量的作用域就是函数的范围，且在词法分析阶段已经确定了，能否为某个变量动态植入到指定作用域里呢，达到类似<code>欺骗式的词法作用域</code>的效果？当然是可以的！</li>
<li><strong>JavaScript有两种机制实现所谓的<code>欺骗词法</code>：<code>eval</code>和<code>with</code>。</strong> 虽然滥用欺骗词法有可能会带来性能问题，不推荐使用。但不妨碍我们通过它，从而进一步的深入了解JavaScript作用域。<h4 id="eval-函数"><a href="#eval-函数" class="headerlink" title="eval()函数"></a><code>eval()</code>函数</h4></li>
<li><strong><code>eval()</code>函数接收一个代码字符串作为参数，通知JS引擎来执行它。</strong> 字符串代码中的作用域，动态的以eval()函数执行所在的作用域为准。<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">str, a</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">eval</span>(str);</span><br><span class="line">    <span class="built_in">console</span>.log(a, b);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">2</span>;</span><br><span class="line">foo(<span class="string">&quot;var b = 3;&quot;</span>, <span class="number">1</span>);  <span class="comment">//输出 1, 3</span></span><br></pre></td></tr></table></figure></li>
<li>由于<code>eval()</code>在<code>foo</code>函数作用域中执行，所以<code>str</code>代码字符串中的变量<code>b</code>动态植入到<code>foo</code>函数作用域，从而执行<code>console.log()</code>输出时，屏蔽了全局作用域中同名的变量<code>b</code></li>
<li>由此可见，<code>eval()</code>函数可以在运行期修改词法分析阶段确定的作用域。值得一提的是，除了<code>eval()</code>函数之外，JavaScript很多原生的函数也具有欺骗词法的作用，比如<code>setTmeout()</code>、<code>setInterval()</code>等。</li>
</ul>
<h4 id="with-函数"><a href="#with-函数" class="headerlink" title="with()函数"></a><code>with()</code>函数</h4><ul>
<li><strong><code>with()</code>函数</strong> 可以交换词法作用域，<strong>通常可以当作重复引用同一个对象中的多个属性的快捷方式。</strong><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">    a : <span class="number">1</span>,</span><br><span class="line">    b : <span class="number">2</span>,</span><br><span class="line">    c : <span class="number">3</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//正常的调用需要重复的引用Obj对象</span></span><br><span class="line">obj.a = <span class="number">10</span>;</span><br><span class="line">obj.b = <span class="number">20</span>;</span><br><span class="line">obj.c = <span class="number">30</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//单通过with可以构造一个，obj对象引用的快捷方式</span></span><br><span class="line"><span class="function"><span class="title">with</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//with代码内this默认指向obj对象</span></span><br><span class="line">    a = <span class="number">10</span>;</span><br><span class="line">    b = <span class="number">20</span>;</span><br><span class="line">    c = <span class="number">30</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li>前面我们一直说，欺骗词法会引发性能问题，我们针对<code>with()</code>函数举个例子，看看如何造成全局变量污染的：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//定义一个foo方法</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//方法体中，通过with快捷方式对传入的对象进行赋值操作</span></span><br><span class="line">    <span class="function"><span class="title">with</span>(<span class="params">obj</span>)</span>&#123;</span><br><span class="line">        a = <span class="number">2</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//定义对象obj1，包含a属性</span></span><br><span class="line"><span class="keyword">var</span> obj1 = &#123;</span><br><span class="line">    a : <span class="number">3</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//定义对象obj2，不包含a属性</span></span><br><span class="line"><span class="keyword">var</span> obj2 = &#123;</span><br><span class="line">    b : <span class="number">3</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//调用foo函数，并传入obj1对象作为参数</span></span><br><span class="line">foo(obj1);</span><br><span class="line"><span class="built_in">console</span>.log(obj1.a);    <span class="comment">//输出 2，foo()方法将a属性成功改为2</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//调用foo函数，并传入obj2对象作为参数</span></span><br><span class="line">foo(obj2);</span><br><span class="line"><span class="built_in">console</span>.log(obj2.a);    <span class="comment">//输出 undefined，由于obj2对象没有a属性，所以赋值失败</span></span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">//输出2，属性a的赋值，暴露到了全局作用域上了</span></span><br></pre></td></tr></table></figure></li>
<li>如以上代码所示，<code>with()</code>函数有可能将赋值的属性转移给全局作用域，这也正是<code>with</code>与<code>eval</code>的区别：<ul>
<li><code>eval()</code>可以动态修改词法作用域；</li>
<li><code>with()</code>是根据传递的对象，凭空创建一个全新的词法作用域；所以当<code>obj2</code>作为参数进行<code>with</code>赋值操作的时候，由于<code>a</code>属性不存在，所以执行正常的LHS查询。</li>
</ul>
</li>
</ul>
<h4 id="性能"><a href="#性能" class="headerlink" title="性能"></a>性能</h4><ul>
<li><code>eval</code>和<code>with</code>会导致全局作用域的变量污染，这只是造成性能问题的一个方面。</li>
<li>除此之外，JavaScript引擎在编译阶段，会对代码进行性能优化，此类工作依赖于代码是静态的词法作用域。因为这是确定了作用域位置的变量，而如果是<code>eval</code>和<code>with</code>的方式，引擎则直接忽略，完全不做任何优化。</li>
<li>并且如果项目中大量使用<code>eval</code>和<code>with</code>进行动态作用域指定，最后参与编码的开发者也会懵逼。 <strong>我们应该秉承JS引擎的规则，将变量限制在最小范围内。</strong></li>
</ul>
<h2 id="2-3-小结"><a href="#2-3-小结" class="headerlink" title="2.3 小结"></a>2.3 小结</h2><ul>
<li><strong>JavaScript有两种机制欺骗词法：<code>eval</code>和<code>with</code>：<code>eval</code>可以动态调用JS引擎执行传入的代码字符串，由此来修改词法作用域；<code>with</code>可以将一个对象的引用，创建一个新的作用域来处理。</strong></li>
<li><strong>由于这两种机制，JS引擎无法在编译阶段对作用域查找进行优化，所以警惕滥用此类函数，从而造成性能问题。</strong></li>
</ul>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E01/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/murmur/reading_notes/%E3%80%8A%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84JavaScript-%E4%B8%8A-%E3%80%8BS01E01/" class="post-title-link" itemprop="url">《你不知道的JavaScript(上)》S01E01</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-11-29 15:09:24" itemprop="dateCreated datePublished" datetime="2020-11-29T15:09:24+08:00">2020-11-29</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2020-12-01 23:07:30" itemprop="dateModified" datetime="2020-12-01T23:07:30+08:00">2020-12-01</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/%E4%B8%80%E5%91%A8%E4%B8%80%E7%AB%A0%E5%89%8D%E7%AB%AF%E4%B9%A6/" itemprop="url" rel="index"><span itemprop="name">一周一章前端书</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>2.4k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>2 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="第1章：作用域是什么"><a href="#第1章：作用域是什么" class="headerlink" title="第1章：作用域是什么"></a>第1章：作用域是什么</h1><ul>
<li>我们通过<code>var</code>声明变量时，是否考虑过这些问题：<ul>
<li>这些变量都存储在哪里？</li>
<li>程序用到它们时，又是怎么找到它们的？</li>
</ul>
</li>
<li>而答案就是：不仅仅是JavaScript，任何编程语言都会设计一套良好的规则来存取变量，而这套规则就叫做 <strong>作用域</strong> 。</li>
</ul>
<h2 id="1-1-编译原理"><a href="#1-1-编译原理" class="headerlink" title="1.1 编译原理"></a>1.1 编译原理</h2><ul>
<li>虽然和静态语言(比如Java)不同，JavaScript是“解释性”的动态语言。</li>
<li>但实际上，JavaScript代码在运行之前也是需要编译的，并且JavaScript引擎编译的步骤，和传统的编译语言非常相似，大致有以下三大步骤：<h5 id="第1步：分词-词法分析（Tokenizing-Lexing）"><a href="#第1步：分词-词法分析（Tokenizing-Lexing）" class="headerlink" title="第1步：分词/词法分析（Tokenizing/Lexing）"></a>第1步：分词/词法分析（Tokenizing/Lexing）</h5></li>
<li>任何<code>.js</code>文件在解析前，对于JS引擎而言都是一大段文本，不能直接运行。所以当务之急，就是将文本字符串“大卸八块”般的进行分解。</li>
<li>词法分析就是 <strong>将文本内容分解成有意义的词法字符串</strong> （token） 。</li>
<li>比如<code>var a = 2;</code>最终会分解成词法字符串数组，得到 [<code>var</code>、<code>a</code>、<code>=</code>、<code>2</code>、<code>;</code>]，而多余的空格则是无意义的。</li>
</ul>
<h5 id="第2步：解析-语法分析（Parsing）"><a href="#第2步：解析-语法分析（Parsing）" class="headerlink" title="第2步：解析/语法分析（Parsing）"></a>第2步：解析/语法分析（Parsing）</h5><ul>
<li>语法分析则是 <strong>将词法字符串数组转换成 “抽象语法树”</strong> （Abstract Syntax Tree，<strong>AST</strong> ）</li>
<li>比如代码<code>var a = 2;</code>会生成以下具有层次结构的对象<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*变量声明的对象*/</span></span><br><span class="line">VariableDeclaration : &#123;</span><br><span class="line">  <span class="comment">/*变量名为 a*/</span></span><br><span class="line">  Identifier : a,</span><br><span class="line">  <span class="comment">/*变量赋值表达式*/</span></span><br><span class="line">  AssignmentExpression : &#123;</span><br><span class="line">      <span class="comment">/*数值类型为 2*/</span></span><br><span class="line">      NumericLiteral : <span class="number">2</span> </span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h5 id="第3步：代码生成"><a href="#第3步：代码生成" class="headerlink" title="第3步：代码生成"></a>第3步：代码生成</h5><ul>
<li>最后一步就是生成代码， <strong>将AST转换为可执行的机器指令</strong> 。</li>
<li>比如代码<code>var a = 2;</code>会创建一个变量<code>a</code>，并为其分配内存，然后将值<code>2</code>存进这个变量。</li>
</ul>
<h2 id="1-2-理解作用域"><a href="#1-2-理解作用域" class="headerlink" title="1.2 理解作用域"></a>1.2 理解作用域</h2><blockquote>
<p>原书将引擎、编译器以及作用域模拟成三个演员，用来说明在执行一段代码时，三者分别负责的工作。但我稍微做一些改动，将作用域比喻成一个记录清单。</p>
</blockquote>
<ul>
<li>执行JS代码依赖三个东西：<ul>
<li><strong><code>引擎</code></strong> ：负责JS代码的编译和执行</li>
<li><strong><code>编译器</code></strong> ：在引擎工作前，负责语法分析和代码生成</li>
<li><strong><code>作用域</code></strong> ：一个具有严格的规则，专门负责收集并维护所有变量的清单列表，通过它来存取变量</li>
</ul>
</li>
<li>阅读代码 <code>var a = 2;</code> 其实访问了两次作用域，一个是 <strong>在编译器编译时检查变量声明</strong> ，一个是 <strong>引擎运行时检查使用</strong> ：<ul>
<li>如上面所说的，第1步编译器会进行词法分析，第2步将词法单元解析成一个树结构的对象；</li>
<li>在第3步生成代码时，编译器会去查找作用域，检查 是否存在同名的变量，如果没有则声明一个新的变量并赋值 ；</li>
<li>最后引擎运行代码时，会再次通过作用域 检查 是否存在同名的变量，如果有则直接 使用，没有则继续向上查找</li>
</ul>
</li>
<li>引擎执行代码到作用域查找变量，分为两种类型：<strong>RHS查询</strong> 和 <strong>LHS查询</strong> ：<ul>
<li>“L（left）”和“R（right）”分别代表变量处于表达式的左边还是右边；</li>
<li>RHS查询就是查找变量，可理解成retrieve his source value（找到它源值）。比如<code>console.log(a)</code>就是RHS查询，找到变量<code>a</code>的值传递给<code>console.log()</code>；</li>
<li>LHS查询则是查找变量的容器对其进行赋值。比如<code>var a = 2;</code>就是LHS查询，找到变量<code>a</code>并为它赋值<code> = 2</code>；</li>
</ul>
</li>
<li>我们尝试用RHS查询和LHS查询的思维来阅读JS代码：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(a);</span><br><span class="line">&#125;</span><br><span class="line">foo(<span class="number">2</span>);</span><br></pre></td></tr></table></figure>
我们都知道<code>function</code>声明函数的方式等同于，声明一个变量并为其赋值一个执行方法体：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = <span class="function"><span class="keyword">function</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(a);</span><br><span class="line">&#125;</span><br><span class="line">foo(<span class="number">2</span>);</span><br></pre></td></tr></table></figure>
<ul>
<li><code>var foo = function()</code>这是一个LHS查询：声明<code>foo</code>变量并为其赋值一个方法；</li>
<li><code>foo(2)</code>属于RHS查询：找到<code>foo</code>变量的值并执行它</li>
<li>进到<code>foo</code>方法体中，实际上这里隐藏了一句代码<code>a = 2;</code>将传递的值赋值给形参</li>
<li><code>console.log(a)</code>是RHS查询：找到<code>a</code>的值，传递给<code>console.log(...)</code></li>
<li>值得一提的是，<code>console.log()</code>本身也属于RHS查询，会去找寻<code>log()</code>方法的引用并执行它</li>
</ul>
</li>
</ul>
<h2 id="1-3-作用域嵌套"><a href="#1-3-作用域嵌套" class="headerlink" title="1.3 作用域嵌套"></a>1.3 作用域嵌套</h2><ul>
<li>不管是RHS查询还是LHS查询都从当前作用域开始，如果当前作用域无法找到变量时，引擎会转移到外层作用域中继续查找，直至转移到最顶层的作用域，也就是全局作用域。</li>
<li>举例：<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params">a</span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(a + b);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> b = <span class="number">2</span>;</span><br><span class="line">foo(<span class="number">2</span>);</span><br></pre></td></tr></table></figure>
在<code>foo</code>方法体中，变量<code>b</code>在<code>foo</code>的作用域中找不到，将会到外层的全局作用域查找，最后输出4</li>
</ul>
<h2 id="1-4-异常"><a href="#1-4-异常" class="headerlink" title="1.4 异常"></a>1.4 异常</h2><ul>
<li>之所以 区分RHS和LHS，是因为当查找到未声明的变量时，这两种查询的行为是不一样的：<ul>
<li>如前文提到的，LHS查询失败时会在全局作用域创建一个同名的变量；</li>
<li>而RHS查询失败时，则会抛出 <strong>ReferenceError异常</strong> ；另一种情况是，查找到了变量，但是尝试对这个变量的值做不合理的操作（比如对一个非函数的变量进行调用），则抛出TypeError异常</li>
<li>总而言之，RererenceError异常是作用域判别失败相关的， <strong>TypeError异常</strong> 则代表作用域判别成功了，但对结果的操作是非法或不合理的</li>
</ul>
</li>
</ul>
<h2 id="1-5-小结"><a href="#1-5-小结" class="headerlink" title="1.5 小结"></a>1.5 小结</h2><ul>
<li><strong>作用域是一套存取变量的规则</strong> ；</li>
<li>在代码执行前，会先由编译器进行编译，JavaScript引擎在执行代码时会进行LHS查询和RHS查询：<ul>
<li><strong>LHS查询是对变量进行赋值</strong> ，其中<code>=</code>操作符或者调用函数时传参的操作，都会导致相关作用域的赋值操作；</li>
<li><strong>RHS查询是对变量的值进行查找</strong> ；</li>
</ul>
</li>
<li>LHS和RHS查询都会从当前执行作用域开始，<strong>如果当前作用域找不到，就会往上级作用域继续查找，每次上升一级作用域，直至到顶级的全局作用域</strong></li>
<li><strong>不成功的RHS查询会抛出Reference异常，而不成功的LHS查询会自动式地创建一个全局变量</strong></li>
</ul>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>





  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/murmur/page/4/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/murmur/">1</a><span class="space">&hellip;</span><a class="page-number" href="/murmur/page/4/">4</a><span class="page-number current">5</span>
  </nav>



      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
